package com.cim.auth;

import com.cim.config.GlobalConfig;
import com.cim.pojo.Account;
import com.cim.service.AccountService;
import com.cim.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private AccountService accountService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String token=request.getHeader("token");
        String user=TokenUtils.verify(token, GlobalConfig.TOKEN_USER);
        String role=TokenUtils.verify(token,GlobalConfig.TOKEN_ROLE);
        String password=TokenUtils.verify(token,GlobalConfig.TOKEN_PASS);
        if(TokenUtils.verify(token)){
            //验证数据库中密码
//            Account account=accountService.getAccountByUserName(user);    //此处由于accountService注入失败,暂时不验证数据库中的密码变动
            Account account=new Account();
            account.setPassword(password);
            if(password!=null&&account!=null&&password.equals(account.getPassword())){
                request.setAttribute(GlobalConfig.TOKEN_USER,user);
                request.setAttribute(GlobalConfig.TOKEN_ROLE,role);
                return true;
            }else{
                response.sendError(402,"认证失效");
                return false;
            }
        }
        response.sendError(403,"鉴权失败");
        return false;
    }

    /**
     * 设置请求头格式
     * @param res
     */
    public void setResHeader(HttpServletResponse res){
        res.setContentType("application/octet-stream"); //设置返回格式二进制流
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Credentials", "true");
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        res.setHeader("Access-Control-Max-Age", "0");
        res.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
        res.setHeader("XDomainRequestAllowed","1");
    }
    /**
     * 后处理回调方法，实现处理器的后处理（但在渲染视图之前），此时我们可以通过modelAndView（模型和视图对象）对模型数据进行处理或对视图进行处理，modelAndView也可能为null。
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 整个请求处理完毕回调方法，即在视图渲染完毕时回调，如性能监控中我们可以在此记录结束时间并输出消耗时间，还可以进行一些资源清理，类似于try-catch-finally中的finally，
     * 但仅调用处理器执行链中preHandle返回true的拦截器的afterCompletion**。
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
